package com.geen.tuoke.ui.activity

import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.view.View
import android.view.inputmethod.EditorInfo
import androidx.core.view.isVisible
import androidx.recyclerview.widget.LinearLayoutManager
import com.blankj.utilcode.util.ClipboardUtils
import com.blankj.utilcode.util.ToastUtils
import com.chad.library.adapter.base.module.LoadMoreModule
import com.geen.tuoke.MyApplication
import com.geen.tuoke.R
import com.geen.tuoke.base.BaseActivity
import com.geen.tuoke.base.BaseAdapter
import com.geen.tuoke.base.EmptyViewModel
import com.geen.tuoke.bean.CustomerInfo
import com.geen.tuoke.bean.Label
import com.geen.tuoke.bean.SearchTaskInfo
import com.geen.tuoke.bean.TaskTag
import com.geen.tuoke.databinding.*
import com.geen.tuoke.ui.activity.AddOrEditCustomerActivity
import com.geen.tuoke.ui.popupwindow.CustomerFuncPopup
import com.geen.tuoke.ui.viewmodel.SearchTaskVm
import com.geen.tuoke.utils.IntentConstants
import com.geen.tuoke.utils.ext.dp2px
import com.geen.tuoke.utils.ext.initClose
import com.geen.tuoke.widget.CustomLoadMoreView
import com.geen.tuoke.widget.EmptyLayout
import com.qmuiteam.qmui.kotlin.onClick
import com.seeway.wms.utils.startActivity
import kotlinx.android.synthetic.main.include_toolbar.*

/**
 *
 * @Description: 搜索 顾客任务
 * @Author: geen
 * @CreateDate: 2022/1/3 16:42
 * @Version: 1.0
 */
class SearchCustomerActivity : BaseActivity<SearchTaskVm, ActivityTaskSearchBinding>(),
    SearchTaskVm.SearchTaskHandler {

    private lateinit var searchCustomerAdapter: BaseAdapter<CustomerInfo, ItemCustomListBinding>

    override fun getLayoutId(): Int {
        return R.layout.activity_task_search
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        with(mBinding) {
            lifecycleOwner = this@SearchCustomerActivity
            viewModel = mViewModel
            handler = this@SearchCustomerActivity
        }
        initView()

        mViewModel.dataPageCustom.observe(this, {
            if (it == null) {
                return@observe
            }
            //如果有下拉刷新 处理
            if (mViewModel.pageNo == 1) {
                searchCustomerAdapter.setList(it.records)
            } else {
                searchCustomerAdapter.addData(it.records)
            }
            if (mViewModel.pageNo == it.totalPage) {
                searchCustomerAdapter.loadMoreModule.loadMoreEnd()
            } else {
                searchCustomerAdapter.loadMoreModule.loadMoreComplete()
            }
            mViewModel.pageNo++
        })

    }

    private fun initView() {
        mBinding.viewBack.setOnClickListener {
            finish()
        }

        mBinding.etSearch.setOnEditorActionListener { v, actionId, event ->
            when (actionId) {
                EditorInfo.IME_ACTION_SEARCH -> {
                    //调用接口
                    mViewModel.customQuery()
                }
            }
            false
        }

        searchCustomerAdapter = object : BaseAdapter<CustomerInfo, ItemCustomListBinding>(
            R.layout.item_custom_list
        ), LoadMoreModule {
            override fun onUpdate(
                binding: ItemCustomListBinding,
                item: CustomerInfo,
                position: Int
            ) {
                binding.run {
                    data = item

                    loadLabelListUi(this, context, item)

                    ivMore.onClick {
                        CustomerFuncPopup(this@SearchCustomerActivity, {
                            openWx(item.mobile)
                        }, {
                            AddLabelActivity.start(context, item)
                        }, {
                            AddOrEditCustomerActivity.start(
                                ivMore.context,
                                item
                            )
                        }).createPopup<CustomerFuncPopup>()
                            .showAsDropDown(
                                ivMore, -dp2px(125f), -dp2px(60f)
                            )

                    }
                }
            }
        }


        mBinding.mRecycleView.adapter = searchCustomerAdapter
        searchCustomerAdapter.setEmptyView(EmptyLayout(this))
        searchCustomerAdapter.loadMoreModule.loadMoreView = CustomLoadMoreView()
        searchCustomerAdapter.loadMoreModule.isEnableLoadMoreIfNotFullPage = true
        searchCustomerAdapter.loadMoreModule.isEnableLoadMore = true
        searchCustomerAdapter.loadMoreModule.isAutoLoadMore = true

        searchCustomerAdapter.loadMoreModule.setOnLoadMoreListener {
            mViewModel.pageNo = 1
            mViewModel.customQuery()
        }

        searchCustomerAdapter.setOnItemChildClickListener { adapter, view, position ->
            when (view.id) {
                R.id.tvAdd -> {

                }
            }
        }

        //tag
        val tagList = arrayListOf<TaskTag>()
        tagList.add(TaskTag("公司", true, 2))
        tagList.add(TaskTag("电话", false, 0))
        tagList.add(TaskTag("联系人", false, 1))
        tagList.add(TaskTag("备注", false, 3))
        val tagAdapter = object : BaseAdapter<TaskTag, ItemTaskSearchTagBinding>(
            R.layout.item_task_search_tag,
            tagList
        ) {
            override fun onUpdate(binding: ItemTaskSearchTagBinding, item: TaskTag, position: Int) {
                binding.run {
                    tvName.isSelected = item.isSelect
                    tvName.text = tagList.get(position).tagName
                }
            }
        }

        tagAdapter.setOnItemClickListener { adapter, view, position ->
            tagAdapter.data.forEach {
                it.isSelect = false
            }
            mViewModel.currentTaskTag.value = tagAdapter.getItem(position)
            tagAdapter.getItem(position).isSelect = true
            mViewModel.pageNo = 1
            tagAdapter.notifyDataSetChanged()
        }

        mViewModel.currentTaskTag.value = tagList[0]

        mBinding.mTagRecycleView.adapter = tagAdapter
    }

    private fun loadLabelListUi(
        itemCustomListBinding: ItemCustomListBinding,
        context: Context,
        item: CustomerInfo
    ) {

        itemCustomListBinding.rvLabel.isVisible = item.labels.isNotEmpty()

        itemCustomListBinding.rvLabel.layoutManager =
            LinearLayoutManager(context, LinearLayoutManager.HORIZONTAL, false)
        itemCustomListBinding.rvLabel.adapter =
            object : BaseAdapter<Label, ItemCustomerLabelBinding>(
                R.layout.item_customer_label,
                item.labels.toMutableList()
            ) {
                override fun onUpdate(
                    binding: ItemCustomerLabelBinding,
                    item: Label,
                    position: Int
                ) {
                    binding.tvLabel.text = item.name
                }

                override fun getItemCount(): Int {
                    //防止标签太多 这里先限制3个
                    return if (super.getItemCount() > 3) 3 else super.getItemCount()
                }
            }
    }

    private fun openWx(item: String) {
        ClipboardUtils.copyText(item)
        try {
            val intent = Intent(Intent.ACTION_MAIN)
            intent.addCategory(Intent.CATEGORY_LAUNCHER)
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
            intent.component = MyApplication.instance.getPackageManager()
                .getLaunchIntentForPackage("com.tencent.mm")?.component
            startActivity(intent)
        } catch (e: Exception) {
            ToastUtils.showShort("设备无微信")
            e.printStackTrace()
        }
    }

    override fun clickCancel(view: View) {
        mViewModel.queryContent.value = null
        searchCustomerAdapter.setList(arrayListOf())
    }

}